// pages/shoppingcar/shoppingcar.js
// 获取应用实例
var ports = require("../../utils/ports.js")
var utils = require("../../utils/util.js");
const app = getApp()
Component({
  /**
   * 页面的初始数据
   */
  data: {
    botH: '0px',
    editable: false,
    total: '0.00',
    checkAll: false,
    isLogin: false
  },
  attached: function () {
    this.setData({
      botH: app.globalData.bottomHeight + 'px'
    })
    this.init()
  },
  methods: {
    init() {
      var that = this
      var sessionID = wx.getStorageSync('USER_SESSIONID')
      var member = wx.getStorageSync('USER_MEMBER')
      if (sessionID && !member) {
        that.getOneMemberDetail()
      } else if (member) {
        that.setData({
          member: member
        })
      }
      if (sessionID) {
        that.getCartList()
      }
    },
    enterAni() {
      var that = this
      //进入动画
      var animation = wx.createAnimation({
        duration: 1000,
        timingFunction: 'ease',
        delay: 0
      });
      animation.opacity(1).translateY(0).step()
      that.setData({
        ani: animation.export()
      })
    },
    outAni() {
      var that = this
      //清除动画
      var animation = wx.createAnimation({
        duration: 10,
        timingFunction: 'ease',
        delay: 0
      });
      animation.opacity(0.2).translateY(30).step()
      that.setData({
        ani: animation.export()
      })
    },
    //购物车列表
    getCartList() {
      var that = this
      ports.ModuleCart.getCartList({}, that, res => {
        if (res.data.header.code == 0) {
          that.setData({
            isLogin: true,
            cartList: res.data.body.data,
            goodsList: res.data.body.data[0].goodsList.reverse()
          })
          that.total_edit()
        } else if (res.data.header.code == 10123) {
          that.setData({
            isLogin: true,
            cartList: [],
            total: '0.00',
            checkAll: false
          })
        } else {
          wx.showToast({
            title: res.data.header.msg,
            icon: 'none'
          })
        }
      })
    },
    //进入授权页面
    getUserProfile(e) {
      let that = this
      wx.getUserProfile({
        desc: '用于完善会员资料',
        success: (res) => {
          if (res.userInfo != null) {
            wx.setStorageSync("USER_DEFAULT", {
              avatarUrl: res.userInfo.avatarUrl,
              nickName: res.userInfo.nickName
            })
            utils.doLoginOther((data) => {
              that.setData({
                member: data,
                isLogin: true
              })
              that.init()
            })
          }
        }
      })
    },
    getOneMemberDetail() {
      let that = this
      ports.ModuleMember.getOneMemberDetail({}, that, res => {
        that.setData({
          member: res.data.body
        })
        wx.setStorageSync("USER_MEMBER", res.data.body)
      })
    },

    //进入商品详情
    toGoodsDetail: function (e) {
      wx.navigateTo({
        url: '/pages/proInfo/proInfo?id=' + e.currentTarget.dataset.id,
      })
    },
    //减数量
    countdown: function (e) {
      var that = this
      var dataset = e.currentTarget.dataset
      var pindex = dataset.pindex //第一层index
      var index = dataset.index //第二层index
      var cartList = that.data.cartList
      var cartGoods = cartList[parseInt(pindex)].goodsList[parseInt(index)]
      if (cartGoods.qty == 1) {
        return
      }
      //参数
      let data = {}
      data.cartGoodsID = cartGoods.id
      data.qty = cartGoods.qty - 1
      ports.ModuleCart.updateCartGoodsNumber(data, that, res => {
        if (res.data.header.code == 0) {
          cartList[parseInt(pindex)].goodsList[parseInt(index)].qty = data.qty
          cartList[parseInt(pindex)].goodsList[parseInt(index)].priceTotal = data.qty *
            cartList[parseInt(pindex)].goodsList[parseInt(index)].priceNow
          that.setData({
            cartList: cartList
          })
          that.total_edit()
        } else {
          wx.showToast({
            title: res.data.header.msg,
            icon: 'none'
          })
        }
      })
    },
    //加数量
    countadd: function (e) {
      var that = this
      var dataset = e.currentTarget.dataset
      var pindex = dataset.pindex //第一层index
      var index = dataset.index //第二层index
      var cartList = that.data.cartList
      var cartGoods = cartList[parseInt(pindex)].goodsList[parseInt(index)]
      //参数
      let data = {}
      data.cartGoodsID = cartGoods.id
      data.qty = cartGoods.qty + 1
      ports.ModuleCart.updateCartGoodsNumber(data, that, res => {
        if (res.data.header.code == 0) {
          cartList[parseInt(pindex)].goodsList[parseInt(index)].qty = data.qty
          cartList[parseInt(pindex)].goodsList[parseInt(index)].priceTotal = data.qty *
            cartList[parseInt(pindex)].goodsList[parseInt(index)].priceNow
          that.setData({
            cartList: cartList
          })
          that.total_edit()
        } else {
          wx.showToast({
            title: res.data.header.msg,
            icon: 'none'
          })
        }
      })
    },
    //更改数量
    updateAmount: function (e) {
      var that = this
      var dataset = e.currentTarget.dataset
      var pindex = dataset.pindex //第一层index
      var index = dataset.index //第二层index
      var cartList = that.data.cartList
      var cartGoods = cartList[parseInt(pindex)].goodsList[parseInt(index)]

      //参数
      let data = {}
      data.cartGoodsID = cartGoods.id
      data.qty = parseInt(e.detail.value)
      ports.ModuleCart.updateCartGoodsNumber(data, that, res => {
        if (res.data.header.code == 0) {
          cartList[parseInt(pindex)].goodsList[parseInt(index)].qty = data.qty
          cartList[parseInt(pindex)].goodsList[parseInt(index)].priceTotal = data.qty *
            cartList[parseInt(pindex)].goodsList[parseInt(index)].priceNow
          that.setData({
            cartList: cartList
          })
          that.total_edit()
        } else {
          wx.showToast({
            title: res.data.header.msg,
            icon: 'none'
          })
        }
      })
    },
    //删除
    delPro: function (e) {
      var that = this
      var dataset = e.currentTarget.dataset
      var pindex = dataset.pindex //第一层index
      var index = dataset.index //第二层index
      var cartList = that.data.cartList
      var cartGoods = cartList[parseInt(pindex)].goodsList[parseInt(index)]

      //参数
      let data = {}
      data.cartGoodsID = cartGoods.id
      ports.ModuleCart.removeCartGoods(data, that, res => {
        if (res.data.header.code == 0) {
          cartList[pindex].goodsList.splice(index, 1);
          if (cartList[pindex].goodsList.length == 0) {
            cartList.splice(pindex, 1);
          }
          that.setData({
            cartList: cartList
          })
          that.total_edit()
          wx.showToast({
            title: "删除成功！",
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: res.data.header.msg,
            icon: 'none'
          })
        }
      })
    },
    //编辑
    editorder() {
      this.setData({
        editable: !this.data.editable
      })
    },
    //结算
    toConfirmOrder() {
      var cartList = this.data.cartList
      var ntotalprice = this.data.total
      if (cartList.length == 0) {
        wx.showToast({
          title: '购物车为空',
          icon: 'none'
        })
        return
      } else if (ntotalprice <= 0) {
        wx.showToast({
          title: '请选择商品',
          icon: 'none'
        })
        return
      } else {
        wx.navigateTo({
          url: '/pages/confirmOrder/confirmOrder?type=cart',
        })
      }
    },
    //单个按钮选中状态
    productCheck(e) {
      var that = this
      var dataset = e.currentTarget.dataset
      var pindex = dataset.pindex //第一层index
      var index = dataset.index //第二层index
      var cartList = that.data.cartList
      var cartGoods = cartList[parseInt(pindex)].goodsList[parseInt(index)]

      //参数
      let data = {}
      data.cartGoodsID = cartGoods.id
      data.isSelect = cartGoods.isSelected == 1 ? 2 : 1
      ports.ModuleCart.selectCartGoods(data, that, res => {
        if (res.data.header.code == 0) {
          cartList[parseInt(pindex)].goodsList[parseInt(index)].isSelected = data.isSelect
          that.setData({
            cartList: cartList
          })
          that.total_edit()
        } else {
          wx.showToast({
            title: res.data.header.msg,
            icon: 'none'
          })
        }
      })
    },
    //全选状态
    allProductCheck() {
      var that = this
      var cartList = that.data.cartList
      if (cartList.length == 0 || cartList[0].goodsList.length == 0) {
        return
      }
      var isSelected = that.data.checkAll ? 2 : 1
      var goodsList = cartList[0].goodsList
      var cartGoodsID = ''
      for (var i = 0; i < goodsList.length; i++) {
        goodsList[i].isSelected = isSelected
        cartGoodsID += goodsList[i].id + ','
      }

      let data = {}
      data.cartGoodsID = cartGoodsID
      data.isSelect = isSelected
      ports.ModuleCart.selectCartGoods(data, that, res => {
        if (res.data.header.code == 0) {
          cartList[0].goodsList = goodsList
          that.setData({
            cartList
          })
          that.total_edit()
        } else {
          wx.showToast({
            title: res.data.header.msg,
            icon: 'none'
          })
        }
      })
    },
    //计算是否全选，金额
    total_edit() {
      var that = this
      var cartList = that.data.cartList
      var total = 0;
      if (cartList.length == 0 || cartList[0].goodsList.length == 0) {
        that.setData({
          checkAll: false,
          total: total.toFixed(2)
        })
        return
      }
      var goodsList = cartList[0].goodsList
      var checkAll = true
      for (var i = 0; i < goodsList.length; i++) {
        if (goodsList[i].isSelected != 1) {
          checkAll = false
        } else {
          total += goodsList[i].priceTotal
        }
      }
      that.setData({
        checkAll,
        total: total.toFixed(2)
      })
    },
    onPullDownRefresh() {
      var that = this;
      ports.ModuleAll.PullDownRefresh(that, res => {
        that.getCartList()
      })
    }
  },
  pageLifetimes: {
    show() {
      this.init()
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selected: 2
        })
      }
      this.enterAni()
    },
    hide() {
      this.outAni()
    }
  }
})